import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import quandl
import datetime
from scipy.stats import norm
import math
plt.rcParams['figure.figsize'] = (15,8)
%matplotlib inline
## This is small code to correct btc.csv file from coindesk. Because that csv has one extra comma at end.
#f = open('btc2.csv','a')
#for line in open('btc.csv').readlines():
# l = line.strip('\n').strip(',')
# f.write(l+'\n')
#f.close()
df = pd.read_csv('bt.csv',index_col='Date', parse_dates=True,
engine='python')
df2 = pd.read_csv('BTC.csv', index_col='date',parse_dates=True,names=['date','ranknow','open','high','low','close'],
engine='python',skiprows=1)
df3 = pd.read_csv('btc2.csv',index_col='date',parse_dates=True,
names=['date','txVolume(USD)','adjustedTxVolume(USD)','txCount','marketcap(USD)','price(USD)',
'exchangeVolume(USD)', 'generatedCoins','fees','activeAddresses', 'averageDifficulty',
'paymentCount','medianTxValue(USD)', 'medianFee','blockSize','blockCount'],
skiprows=1)
df3.dtypes
df3.dropna(subset=['txVolume(USD)','marketcap(USD)'],inplace=True)
df3.fillna(0,inplace=True)
df3.dtypes
df.plot(figsize=(14,7),logy=True)
df2.plot(figsize=(14,8),logy=True)
#bitcoin = quandl.get("BCHAIN/MKPRU")
#bitcoin['Value'].replace(0, np.nan, inplace=True)
#bitcoin = bitcoin.dropna()
#bitcoin.Value.plot(logy=True,figsize=(15,8));
#plt.legend()
df['Returns'] = (df['Daily Closing Price'].pct_change()+1).fillna(0)
#df.head()
dates = pd.date_range(start=datetime.date.today(),end='2018-12-30')
np.random.seed(1234)
simulated_returns_bitcoin = np.random.choice(df.Returns, size=(len(dates), 100))
sim_bitcoin_returns = pd.DataFrame(data=simulated_returns_bitcoin, index=dates)
#print(sim_bitcoin_returns.shape)
cum_sim_bitcoin = sim_bitcoin_returns.cumprod(axis=0)
#print(cum_sim_bitcoin.shape)
future = pd.DataFrame(data=cum_sim_bitcoin, index=dates)
future = future * df['Daily Closing Price'][-1]
future.head()
cum_sim_bitcoin.plot(logy=True,legend=False,figsize=(15,8))
future.plot(legend=False, figsize=(15,8))
future.plot(logy=True,legend=False, figsize=(15,8),
title='Bitcoin price Monte Carlo simulations until Dec 31st 2018')
plt.xlabel('Date')
plt.ylabel("Price ($)")
df3[['txVolume(USD)','marketcap(USD)']].plot(figsize=(15,8),logy=True)
df3[['exchangeVolume(USD)','marketcap(USD)']].plot(figsize=(15,8),logy=True)
df3['NVT'] = df3['marketcap(USD)'] / df3['txVolume(USD)']
df3.fillna(0,inplace=True)
df3.tail(5)['NVT']
df3[['NVT']].plot(figsize=(15,8))
o = np.convolve(list(reversed(list(df3.NVT.values))), np.ones((14,))/14., mode='same')
o = list(reversed(o))
#print(o)
df3['SMOOTH_NVT'] = o
df3['SMOOTH_NVT'] = np.convolve(df3.NVT.values, np.ones((14,))/14., mode='same')
df3['SMOOTH_NVT'][:5]
plt.figure(figsize=(15,8))
plt.plot(df3.index,df3.NVT,color='grey',label='NVT')
plt.plot(df3.index, df3.SMOOTH_NVT,color = 'red',label='SMOOTH NVT')
plt.legend(loc='best')
plt.xlabel('Date')
plt.ylabel('NVT/SMOOTH NVT Ratio')
plt.title('NVT/SMOOTH NVT Ratio')
#df3[['NVT','SMOOTH_NVT']].plot(figsize=(15,8),colormap=plt.cm.Set2_r)
df3['MCAP'] = df3['marketcap(USD)'] / 10e9
plt.figure(figsize=(15,8))
plt.plot(df3.index,df3.NVT,color='grey',label='NVT')
plt.plot(df3.index,df3.SMOOTH_NVT,color='black',label='SMOOTH NVT')
plt.plot(df3.index,df3.MCAP,color='orange',label='Scaled Market Cap(in Bn)')
plt.legend(loc='best')
plt.xlabel('Date')
plt.ylabel('NVT/SMOOTH NVT/ Market Cap')
df3[['NVT','SMOOTH_NVT','MCAP']].plot(figsize=(15,8),colormap=plt.cm.Set2_r,logy=True)
df3.index.name = 'Date'
df3[['exchangeVolume(USD)','marketcap(USD)']].plot(figsize=(15,8))
plt.figure(figsize=(15,8))
plt.plot(df3.index,df3['exchangeVolume(USD)']/1e9,color='orange',label='Exchange Volume (in Bn)')
plt.plot(df3.index,df3['marketcap(USD)']/1e9,color='blue',label='Market Cap (in Bn)')
plt.legend(loc='best')
plt.xlabel('Date')
plt.ylabel('Exchange Vol/ Market Cap')
df3[['exchangeVolume(USD)','marketcap(USD)']].plot(figsize=(15,8))
#df3.reset_index(inplace=True)
#df3.Date = [datetime.date(d.year,d.month,1) for d in df3.Date]
#df3 = df3.groupby(['Date']).sum()
#df3[['NVT','SMTH_NVT','MCAP']].plot(figsize=(15,8),colormap=plt.cm.Set2_r)
plt.figure(figsize=(12,6))
plt.plot(df3.index.values,df3['txVolume(USD)'].values)
l,t = plt.yticks([0,10e9,20e9,30e9,40e9,50e9],['0 Bn','10 Bn','20 Bn','30 Bn','40 Bn','50 Bn'])
#plt.plot(df3.index.values,df3['marketcap(USD)'].values)
plt.xlabel('Year')
plt.ylabel('txVolume(USD)')
#plt.axes()
#plt.plot(df3.index.values,df3['marketcap(USD)'].values)
df3['NVT_R'] = (df3['NVT'].pct_change()+1).fillna(0)
dates = pd.date_range(start=datetime.date.today(),end='2018-12-30')
np.random.seed(1234)
simulated_nvt = np.random.choice(df3.NVT_R, size=(len(dates), 100))
sim_nvt = pd.DataFrame(data=simulated_nvt, index=dates)
cum_sim_nvt = sim_nvt.cumprod(axis=0)
future2 = pd.DataFrame(data=cum_sim_nvt, index=dates)
future2 = future2 * df3['NVT'][-1]
future2.plot(legend=False, figsize=(15,8),
title='Bitcoin NVT ratio Monte Carlo simulations until Dec 31st 2018')
plt.xlabel('Date')
plt.ylabel("NVT")
df3['txVolume_R'] = (df3['txVolume(USD)'].pct_change()+1).fillna(0)
dates = pd.date_range(start=datetime.date.today(),end='2018-12-30')
np.random.seed(1234)
simulated_tx_vol = np.random.choice(df3.txVolume_R, size=(len(dates), 100))
sim_tx_vol = pd.DataFrame(data=simulated_tx_vol, index=dates)
cum_sim_tx_vol = sim_tx_vol.cumprod(axis=0)
future3 = pd.DataFrame(data=cum_sim_tx_vol, index=dates)
future3 = future3 * df3['txVolume(USD)'][-1]
df3['marketcap_R'] = (df3['marketcap(USD)'].pct_change()+1).fillna(0)
dates = pd.date_range(start=datetime.date.today(),end='2018-12-30')
np.random.seed(1234)
simulated_marketcap_R = np.random.choice(df3.marketcap_R, size=(len(dates), 100))
sim_marketcap_R = pd.DataFrame(data=simulated_marketcap_R, index=dates)
cum_sim_marketcap_R = sim_marketcap_R.cumprod(axis=0)
future4 = pd.DataFrame(data=cum_sim_marketcap_R, index=dates)
future4 = future4 * df3['marketcap(USD)'][-1]
df4 = pd.DataFrame(data = future4.values / future3.values)
df4 = df4.set_index(future4.index)
future3.plot(legend=False, figsize=(15,8), title='Bitcoin Transaction Volume Monte Carlo simulations until Dec 31st 2018')
plt.xlabel('Date')
plt.ylabel("Transaction Volume")
future4.plot(legend=False, figsize=(15,8), title='Bitcoin market Cap Monte Carlo simulations until Dec 31st 2018')
plt.xlabel('Date')
plt.ylabel("Market Cap")
df4.plot(legend=False, figsize=(15,8),
title='Bitcoin NVT ratio Monte Carlo simulations until Dec 31st 2018')
plt.Circle((2000,'2018-09-01'),20,visible=True,fill=True)
plt.xlabel('Date')
plt.ylabel("NVT")
df3.head()
future2.plot(legend=False, figsize=(15,8),
title='Bitcoin NVT ratio Monte Carlo simulations until Dec 31st 2018')
plt.xlabel('Date')
plt.ylabel("NVT")
#plt.axhline(y=50000,xmin=0,xmax=10000,color='blue')
#plt.axvline(x=50,ymin=0,ymax=10000,color='blue')
fig = plt.figure(figsize=(8,6))
Xt = np.linspace(0,2.5,100)
c = 0.5
for alpha in [0.1, 0.5, 1.0, 2.0]:
plt.plot(Xt,np.exp(Xt*alpha*-2),label='Alpha %s'%alpha)
t = zip(Xt,np.exp(Xt*alpha*-2))
location = [(j,i) for j,i in enumerate(t) if str(i[1])[:3] == '0.5']
#print(location)
plt.plot(Xt[location[0][0]:],[c]*len(Xt[location[0][0]:]),color='black',label='c %s'%c)
y2 = np.array(len(Xt)*[c])
upper = zip(Xt,np.exp(Xt*2.1*-2))
plt.fill_between(Xt, y2 ,np.exp(Xt*0.1*-2), alpha=0.3)
plt.fill_between(Xt, y2, np.exp(Xt*2.0*-2), where= Xt > location[0][1][0], alpha=0.3)
plt.xlabel('Xt')
plt.ylabel('e^-2aXt')
plt.legend(loc='best')
def get_brownian(n):
# Process parameters
#delta = 0.25
delta = 1.0/250.0
#dt = 1.0/250.0
dt = 1.0
# Initial condition.
x = 0.0
Wt = [0.0]
# Iterate to compute the steps of the Brownian motion.
for k in range(n):
x = x + norm.rvs(scale=delta**2*dt)
Wt.append(x)
return Wt
def brownian_path(N):
Δt_sqrt = math.sqrt(1 / N)
Z = np.random.randn(N)
Z[0] = 0
B = np.cumsum(Δt_sqrt * Z)
return B
from math import sqrt
from scipy.stats import norm
import numpy as np
def brownian(x0, n, dt, delta, out=None):
"""
Generate an instance of Brownian motion (i.e. the Wiener process):
X(t) = X(0) + N(0, delta**2 * t; 0, t)
where N(a,b; t0, t1) is a normally distributed random variable with mean a and
variance b. The parameters t0 and t1 make explicit the statistical
independence of N on different time intervals; that is, if [t0, t1) and
[t2, t3) are disjoint intervals, then N(a, b; t0, t1) and N(a, b; t2, t3)
are independent.
Written as an iteration scheme,
X(t + dt) = X(t) + N(0, delta**2 * dt; t, t+dt)
If `x0` is an array (or array-like), each value in `x0` is treated as
an initial condition, and the value returned is a numpy array with one
more dimension than `x0`.
Arguments
---------
x0 : float or numpy array (or something that can be converted to a numpy array
using numpy.asarray(x0)).
The initial condition(s) (i.e. position(s)) of the Brownian motion.
n : int
The number of steps to take.
dt : float
The time step.
delta : float
delta determines the "speed" of the Brownian motion. The random variable
of the position at time t, X(t), has a normal distribution whose mean is
the position at time t=0 and whose variance is delta**2*t.
out : numpy array or None
If `out` is not None, it specifies the array in which to put the
result. If `out` is None, a new numpy array is created and returned.
Returns
-------
A numpy array of floats with shape `x0.shape + (n,)`.
Note that the initial value `x0` is not included in the returned array.
"""
x0 = np.asarray(x0)
# For each element of x0, generate a sample of n numbers from a
# normal distribution.
print(x0.shape + (n,))
r = norm.rvs(size=x0.shape + (n,), scale=delta*math.sqrt(dt))
# If `out` was not given, create an output array.
if out is None:
out = np.empty(r.shape)
# This computes the Brownian motion by forming the cumulative sum of
# the random samples.
np.cumsum(r, axis=-1, out=out)
# Add the initial condition.
out += np.expand_dims(x0, axis=-1)
return out
def get_series():
dt = 1.0 / 250.0
tim = np.arange(0.0,4.0,dt)
alpha = 1.0
eta = 0.1
c = 0.5
Xt = np.zeros(len(tim)+1)
dWt = brownian_path(len(tim))
eq,eq10 = np.log(0.5) / (-2.0 * alpha),np.log(0.05) / (-2.0 * alpha)
for i in range(len(tim)):
t = np.exp(-2.0 * alpha * Xt[i])
tf = t - c
dXt = (eta * tf * dt) + dWt[i]
Xt[i+1] = dXt
return np.array(Xt),tim,eq,eq10
#Xt,eq,eq10 = get_series()
Xt,tim,eq,eq10 = get_series()
#Xt = np.exp(Xt)
fig = plt.figure(figsize=(8,6))
plt.plot(tim,Xt[:len(tim)])
plt.plot(tim, len(tim)*[0.0],linestyle='dashed',label='Intial Point',color='green')
plt.plot(tim, len(tim)*[eq10],linestyle='dashed',label = '10% of Equilbrium Level',color='red')
plt.plot(tim, len(tim)*[eq],linestyle='dashed',label = 'Equilbrium Level',color='black')
plt.xlabel('Time (Years)')
plt.ylabel('Xt')
plt.legend(loc='best')
ixic = pd.read_csv('^IXIC.csv',index_col='Date',parse_dates=True)
ssec = pd.read_csv('^SSEC.csv',index_col='Date',parse_dates=True)
ixic.head(5)
ssec.head(5)
#ixic.index.name = 'Date'
t1 = [int(i) for i in '1997-01-02'.split('-')] # (P0 = 1, 280), (Pt = 1, 436)
t2 = [int(i) for i in '1997-06-26'.split('-')]
X1 = ixic[(ixic.index > pd.to_datetime('1997-01-02')) & (ixic.index < pd.to_datetime('1997-06-26'))]
t3 = [int(i) for i in '1997-06-26'.split('-')] # (Pt = 1, 436), (P t = 2, 309)
t4 = [int(i) for i in '1999-02-10'.split('-')]
X2 = ixic[(ixic.index > pd.to_datetime('1997-06-26')) & (ixic.index < pd.to_datetime('1999-02-10'))]
t5 = [int(i) for i in '1999-02-10'.split('-')] #(P = 2, 309), (P = 3, 171).
t6 = [int(i) for i in '2000-10-18'.split('-')]
X3 = ixic[(ixic.index > pd.to_datetime('1999-02-10')) & (ixic.index < pd.to_datetime('2000-10-18'))]
XR_hat = 0.67 # (PR = 2, 502).
eta_hat = 0.39
alpha_hat = 0.23
sigma_hat = 0.43
c_hat = 0.73
## OU Process
k_hat, mu_hat,sig_hat = (0.47, 1.09, 0.31)
## BM Process
mw_hat, sigm_hat = (0.25, 0.31)
#ixic[['Close','Adj Close']].plot(figsize=(8,6))
def get_series2(X0, dt , eta_hat,alpha_hat,sigma_hat,c_hat, total ):
tim = np.arange(0.0,total,1)
Xt = np.zeros(len(tim))
dWt = brownian_path(len(tim))
Xt[0] = X0
for i in range(len(tim)-1):
t = np.exp(-2.0 * alpha_hat * (Xt[i]/sigma_hat)) - c_hat
dXt = (eta_hat * t * dt) + dWt[i]
Xt[i+1] = dXt
return np.array(Xt),tim
total = (len(X1)+len(X2)+len(X3))
dt = 1.0 / total
Xt,tim = get_series2(0, dt,eta_hat,alpha_hat,sigma_hat,c_hat,total)
plt.figure(figsize = (8,6))
timespan = list(X1.index)+list(X2.index)+list(X3.index)
plt.plot(timespan,Xt,color='blue',label='Xt Sample path')
adj_price = np.log(np.array(list(X1['Adj Close']/1000)+list(X2['Adj Close']/1000)+list(X3['Adj Close']/1000)))
plt.plot(timespan, adj_price,color='red',label='log of adj close price')
X_F = np.array(list(X1.Close.values)+list(X2.Close.values) + list(X3.Close.values))
#X_F = [X1.Close[0]]
X_F += Xt
plt.figure(figsize=(8,6))
plt.plot(list(X1.index)+list(X2.index)+list(X3.index),X_F)
#y = pd.date_range(start='2000-10-18',end='2001-10-10')
plt.figure(figsize=(15,8))
#X = list(X1.index)+list(X2.index)+list(X3.index)
#y = np.array(list(X1.Close)+list(X2.Close)+list(X3.Close))
#plt.plot(X,np.log(y),color='orange')
plt.plot(X1.index, np.log(X1.Close),X2.index, np.log(X2.Close),X3.index, np.log(X3.Close),color='blue')
plt.fill_between(X1.index,np.max(np.log(X1.Close)),np.min(np.log(X1.Close)),alpha=0.4,color='green')
plt.fill_between(X2.index,np.max(np.log(X2.Close)),np.min(np.log(X2.Close)),alpha=0.6,color='yellow')
plt.fill_between(X3.index,np.max(np.log(X3.Close)),np.min(np.log(X3.Close)),alpha=0.6,color='red')
y = pd.date_range(start='2000-10-18',end='2001-10-10')
X4 = ixic[ixic.index.isin(y)]
for i in range(1000):
Xt,tim = get_series2(0,dt,eta_hat,alpha_hat,sigma_hat,c_hat,total)
plt.plot(X4.index, Xt[:len(X4.index)]+np.log(X3.Close[-1]),color='grey')
plt.plot(X4.index, np.log(X4.Close),color='red')
# Shangai
t1 = [int(i) for i in '2006-01-04'.split('-')] # (P0 = 1, 180), (P t = 1,288)
t2 = [int(i) for i in '2006-03-06'.split('-')]
X1 = ssec[(ssec.index > pd.to_datetime('2006-01-04')) & (ssec.index < pd.to_datetime('2006-03-06'))]
t3 = [int(i) for i in '2006-03-06'.split('-')] # (Pt1 = 1, 288), (Pt2 = 4, 053)
t4 = [int(i) for i in '2007-05-30'.split('-')]
X2 = ssec[(ssec.index > pd.to_datetime('2006-03-06')) & (ssec.index < pd.to_datetime('2007-05-30'))]
t5 = [int(i) for i in '2007-05-30'.split('-')] # (P = 4, 053) to (P = 3, 116).
t6 = [int(i) for i in '2008-04-21'.split('-')]
X3 = ssec[(ssec.index > pd.to_datetime('2007-05-30')) & (ssec.index < pd.to_datetime('2008-04-21'))]
XR_hat = 1.23 # (P R = 4, 040).
eta_hat = 0.32
alpha_hat = 0.14
sigma_hat = 0.56
c_hat = 0.70
## OU Process
k_hat, mu_hat,sig_hat = (3.30, 0.97, 1.20)
## BM Process
mw_hat, sigm_hat = (0.44, 0.33)
#ixic[['Close','Adj Close']].plot(figsize=(8,6))
def get_series2(X0, dt , eta_hat,alpha_hat,sigma_hat,c_hat, total ):
tim = np.arange(0.0,total,1)
Xt = np.zeros(len(tim))
dWt = brownian_path(len(tim))
Xt[0] = X0
for i in range(len(tim)-1):
t = np.exp(-2.0 * alpha_hat * (Xt[i]/sigma_hat)) - c_hat
dXt = (eta_hat * t * dt) + dWt[i]
Xt[i+1] = dXt
return np.array(Xt),tim
total = (len(X1)+len(X2)+len(X3))
dt = 1.0 / total
Xt,tim = get_series2(0,dt,eta_hat,alpha_hat,sigma_hat,c_hat,total)
plt.figure(figsize = (8,6))
timespan = list(X1.index)+list(X2.index)+list(X3.index)
plt.plot(timespan,Xt,color='blue',label='Xt Sample path')
adj_price = np.log(np.array(list(X1['Adj Close']/1000)+list(X2['Adj Close']/1000)+list(X3['Adj Close']/1000)))
plt.plot(timespan, adj_price,color='red',label='log of adj close price')
X_F = np.array(list(X1.Close.values)+list(X2.Close.values) + list(X3.Close.values))
X_F += Xt
timespan = list(X1.index)+list(X2.index)+list(X3.index)
plt.figure(figsize=(8,6))
plt.plot(timespan,X_F)
adj_price = np.log(np.array(list(X1['Adj Close'])+list(X2['Adj Close'])+list(X3['Adj Close'])))
#plt.plot(timespan, adj_price,color='red',label='log of adj close price')
#X4[:2],X3[-2:]
plt.figure(figsize=(15,8))
#X = list(X1.index)+list(X2.index)+list(X3.index)
#y = np.array(list(X1.Close)+list(X2.Close)+list(X3.Close))
#plt.plot(X,np.log(y),color='orange')
plt.plot(X1.index, np.log(X1.Close),X2.index, np.log(X2.Close),X3.index, np.log(X3.Close),color='blue')
plt.fill_between(X1.index,np.max(np.log(X1.Close)),np.min(np.log(X1.Close)),alpha=0.4,color='green')
plt.fill_between(X2.index,np.max(np.log(X2.Close)),np.min(np.log(X2.Close)),alpha=0.6,color='yellow')
plt.fill_between(X3.index,np.max(np.log(X3.Close)),np.min(np.log(X3.Close)),alpha=0.6,color='red')
y = pd.date_range(start='2008-04-18',end='2008-11-21')
X4 = ssec[ssec.index.isin(y)]
for i in range(1000):
Xt,tim = get_series2(0,dt,eta_hat,alpha_hat,sigma_hat,c_hat,total)
plt.plot(X4.index, Xt[:len(X4.index)]+np.log(X3.Close[-1]),color='grey')
plt.plot(X4.index, np.log(X4.Close),color='red')
t1 = [int(i) for i in '2016-01-01'.split('-')]
t2 = [int(i) for i in '2016-05-30'.split('-')]
X1 = df[(df.index.date > datetime.date(*t1)) & (df.index.date < datetime.date(*t2))] #(P0 = 433), (Pt1 = 528)
t3 = [int(i) for i in '2016-05-30'.split('-')]
t4 = [int(i) for i in '2017-08-13'.split('-')]
X2 = df[(df.index.date > datetime.date(*t3)) & (df.index.date < datetime.date(*t4))] #(Pt = 528), (Pt = 4,327);
t5 = [int(i) for i in '2017-08-13'.split('-')]
t6 = [int(i) for i in '2017-12-10'.split('-')]
X3 = df[(df.index.date > datetime.date(*t5)) & (df.index.date < datetime.date(*t6))] # (P = 4,327), (P = 14,371).
XR_hat = 2.30 # (PR = 4, 327);
eta_hat = 0.51
alpha_hat = 0.08
sigma_hat = 0.91
c_hat = 0.69
def get_series2(dt , eta_hat,alpha_hat,sigma_hat,c_hat, total ):
tim = np.arange(0.0,total,1)
Xt = np.zeros(len(tim))
dWt = brownian_path(len(tim))
for i in range(len(tim)-1):
t = np.exp(-2.0 * alpha_hat * (Xt[i]/sigma_hat)) - c_hat
dXt = (eta_hat * t * dt) + dWt[i]
Xt[i+1] = dXt
return np.array(Xt),tim
total = (len(X1)+len(X2)+len(X3))
dt = 1.0 / total
Xt,tim = get_series2(dt,eta_hat,alpha_hat,sigma_hat,c_hat,total)
df['Daily Closing Price'].plot(figsize=(15,6))
plt.legend(loc='best')
#df3['txVolume(USD)'].plot(figsize=(15,6), kind='bar',color='red')
plt.figure(figsize=(15,6))
plt.bar(df3.index,df3['txVolume(USD)'].values,color='red',label='Volume')
plt.legend(loc='best')
plt.figure(figsize = (8,6))
plt.plot(list(X1.index)+list(X2.index)+list(X3.index),Xt)
#X_F = np.array(list(X1['Daily Closing Price'].values)+list(X2['Daily Closing Price'].values) + list(X3['Daily Closing Price'].values))
#X_F += Xt
#plt.figure(figsize=(8,6))
#plt.plot(list(X1.index)+list(X2.index)+list(X3.index),X_F)
#plt.plot(list(X1.index)+list(X2.index)+list(X3.index),np.log(X_F))
#plt.figure(figsize=(8,6))
#plt.plot(list(X1.index)+list(X2.index)+list(X3.index),np.log(X_F))
#th = 1;
#mu = 1.2;
#sig = 0.3;
#dt = 1e-2;
#t = np.arange(0,2,dt) # % Time vector
#x = np.zeros(len(t)); #% Allocate output vector, set initial condition
#np.random.seed(1234); # % Set random seed
#for i in range(len(t)-1):
# x[i+1] = x[i]+th*(mu-x[i])*dt+sig*math.sqrt(dt)*np.random.rand();
#plt.plot(t,x);-1
bitcoin_volatility = pd.read_csv('bt.csv',index_col='Date', parse_dates=True,
engine='python')
bitcoin_volatility['Returns'] = bitcoin_volatility['Daily Closing Price'].pct_change().fillna(0)
bitcoin_volatility['Returns'] = bitcoin_volatility['Returns']*100
daily_volatility = bitcoin_volatility['Returns'].std()
sixty_day_volatility = daily_volatility * math.sqrt(6)
plt.figure(figsize=(15,8))
plt.plot(bitcoin_volatility.index,bitcoin_volatility.Returns,label='Daily Percentage change in price.')
plt.xlabel('Time')
plt.ylabel('Percentage change in price')
plt.title('Daily Volatility: %0.2f, 60 day volatility: %0.2f'%(daily_volatility,sixty_day_volatility))
plt.legend(loc='best')
bitcoin_volatility1 = bitcoin_volatility.reset_index()
bitcoin_volatility1.Date = [datetime.date(d.year,d.month,1) for d in bitcoin_volatility1.Date]
bitcoin_volatility1 = bitcoin_volatility1.set_index('Date')
bitcoin_volatility1 = bitcoin_volatility1[['Returns']]
bitcoin_volatility1 = bitcoin_volatility1.groupby(['Date']).std()
daily_volatility = bitcoin_volatility1.std()
sixty_day_volatility = daily_volatility * math.sqrt(6)
plt.figure(figsize=(15,8))
plt.plot(bitcoin_volatility1.index,bitcoin_volatility1.Returns,label='Daily Percentage change in price.')
plt.xlabel('Time')
plt.ylabel('Percentage change in price')
plt.title('Daily Volatility: %0.2f, 60 day volatility: %0.2f'%(daily_volatility,thirty_day_volatility))
plt.legend(loc='best')
ripple = pd.read_csv('ripple.csv',index_col='Date', parse_dates=True,
engine='python')
ripple['Returns'] = ripple['Close'].pct_change().fillna(0)
ripple['Returns'] = ripple['Returns']*100
daily_volatility = ripple['Returns'].std()
sixty_day_volatility = daily_volatility * math.sqrt(6)
plt.figure(figsize=(15,8))
plt.plot(ripple.index,ripple.Returns,label='Daily Percentage change in price.')
plt.xlabel('Time')
plt.ylabel('Percentage change in price')
plt.title('Daily Volatility: %0.2f, 60 day volatility: %0.2f'%(daily_volatility,sixty_day_volatility))
plt.legend(loc='best')
ripple1 = ripple.reset_index()
ripple1.Date = [datetime.date(d.year,d.month,1) for d in ripple1.Date]
ripple1 = ripple1.set_index('Date')
ripple1 = ripple1[['Returns']]
ripple1 = ripple1.groupby(['Date']).std()
daily_volatility = ripple1.std()
sixty_day_volatility = daily_volatility * math.sqrt(12)
plt.figure(figsize=(15,8))
plt.plot(ripple1.index,ripple1.Returns,label='Daily Percentage change in price.')
plt.xlabel('Time')
plt.ylabel('Percentage change in price')
plt.title('Daily Volatility: %0.2f, 60 day volatility: %0.2f'%(daily_volatility,sixty_day_volatility))
plt.legend(loc='best')
litecoin = pd.read_csv('litecoin.csv',index_col='Date', parse_dates=True,
engine='python')
litecoin['Returns'] = litecoin['Close'].pct_change().fillna(0)
litecoin['Returns'] = litecoin['Returns']*100
daily_volatility = litecoin['Returns'].std()
sixty_day_volatility = daily_volatility * math.sqrt(6)
plt.figure(figsize=(15,8))
plt.plot(litecoin.index,litecoin.Returns,label='Daily Percentage change in price.')
plt.xlabel('Time')
plt.ylabel('Percentage change in price')
plt.title('Daily Volatility: %0.2f, 60 day volatility: %0.2f'%(daily_volatility,sixty_day_volatility))
plt.legend(loc='best')
litecoin1 = litecoin.reset_index()
litecoin1.Date = [datetime.date(d.year,d.month,1) for d in litecoin1.Date]
litecoin1 = litecoin1.set_index('Date')
litecoin1 = litecoin1[['Returns']]
litecoin1 = litecoin1.groupby(['Date']).std()
daily_volatility = litecoin1.std()
sixty_day_volatility = daily_volatility * math.sqrt(12)
plt.figure(figsize=(15,8))
plt.plot(litecoin1.index,litecoin1.Returns,label='Daily Percentage change in price.')
plt.xlabel('Time')
plt.ylabel('Percentage change in price')
plt.title('Daily Volatility: %0.2f, 60 day volatility: %0.2f'%(daily_volatility,sixty_day_volatility))
plt.legend(loc='best')
etherium = pd.read_csv('etherium.csv',index_col='Date', parse_dates=True,
engine='python')
etherium['Returns'] = etherium['Close'].pct_change().fillna(0)
etherium['Returns'] = etherium['Returns']*100
daily_volatility = etherium['Returns'].std()
sixty_day_volatility = daily_volatility * math.sqrt(6)
plt.figure(figsize=(15,8))
plt.plot(etherium.index,etherium.Returns,label='Daily Percentage change in price.')
plt.xlabel('Time')
plt.ylabel('Percentage change in price')
plt.title('Daily Volatility: %0.2f, 60 day volatility: %0.2f'%(daily_volatility,sixty_day_volatility))
plt.legend(loc='best')
etherium1 = etherium.reset_index()
etherium1.Date = [datetime.date(d.year,d.month,1) for d in etherium1.Date]
etherium1 = etherium1.set_index('Date')
etherium1 = etherium1[['Returns']]
etherium1 = etherium1.groupby(['Date']).std()
daily_volatility = etherium1.std()
sixty_day_volatility = daily_volatility * math.sqrt(12)
plt.figure(figsize=(15,8))
plt.plot(etherium1.index,etherium1.Returns,label='Daily Percentage change in price.')
plt.xlabel('Time')
plt.ylabel('Percentage change in price')
plt.title('Daily Volatility: %0.2f, 60 day volatility: %0.2f'%(daily_volatility,sixty_day_volatility))
plt.legend(loc='best')